<?php

namespace app\common\controller;

use app\admin\model\Form7;
use app\admin\model\SystemAdmin;
use app\admin\model\TemperatureAlarm;
use app\BaseController;
use app\common\constants\AdminConstant;
use EasyAdmin\tool\CommonTool;
use EasyAdmin\upload\Uploadfile;
use jianyan\excel\Excel;
use think\Exception;
use think\facade\Env;
use think\Model;

/**
 * Class AdminController
 * @package app\common\controller
 */
class AdminController extends BaseController
{

    use \app\common\traits\JumpTrait;

    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;

    /**
     * 字段排序
     * @var array
     */
    protected $sort = [
        'id' => 'desc',
    ];

    /**
     * 当前主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 允许修改的字段
     * @var array
     */
    protected $allowModifyFields = [
        'account_status',
        'status',
        'sort',
        'remark',
        'is_delete',
        'is_auth',
        'title',
    ];

    /**
     * 不导出的字段信息
     * @var array
     */
    protected $noExportFields = ['delete_time', 'update_time'];

    /**
     * 下拉选择条件
     * @var array
     */
    protected $selectWhere = [];

    /**
     * 是否关联查询
     * @var bool
     */
    protected $relationSearch = false;

    /**
     * 模板布局, false取消
     * @var string|bool
     */
    protected $layout = 'layout/default';

    /**
     * 当前用户
     */
    protected $user;

    /**
     * 是否是超级管理员
     */
    protected $isSuper = 0;

    /**
     * 初始化方法
     */
    protected function initialize()
    {
        parent::initialize();
        $this->layout && $this->app->view->engine()->layout($this->layout);

        $this->user = SystemAdmin::find(session('admin.id'));

        if (!empty($this->user)) {
            if ($this->user->id == AdminConstant::SUPER_ADMIN_ID) {
                $this->isSuper = 1;
            }
        }

        $this->assign('isSuper', $this->isSuper);
        $this->assign('user', $this->user);
    }

    /**
     * 模板变量赋值
     * @param string|array $name 模板变量
     * @param mixed $value 变量值
     * @return mixed
     */
    public function assign($name, $value = null)
    {
        return $this->app->view->assign($name, $value);
    }

    /**
     * 解析和获取模板内容 用于输出
     * @param string $template
     * @param array $vars
     * @return mixed
     */
    public function fetch($template = '', $vars = [])
    {
        return $this->app->view->fetch($template, $vars);
    }

    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    /**
     * 构建请求参数
     * @param array $excludeFields 忽略构建搜索的字段
     * @return array
     */
    protected function buildTableParames($excludeFields = [])
    {
        $get = $this->request->get('', null, null);
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 15;
        $filters = isset($get['filter']) && !empty($get['filter']) ? $get['filter'] : '{}';
        $ops = isset($get['op']) && !empty($get['op']) ? $get['op'] : '{}';
        // json转数组
        $filters = json_decode($filters, true);
        $ops = json_decode($ops, true);
        $where = [];
        $excludes = [];

        // 判断是否关联查询
        $tableName = CommonTool::humpToLine(lcfirst($this->model->getName()));

        foreach ($filters as $key => $val) {
            if (in_array($key, $excludeFields)) {
                $excludes[$key] = $val;
                continue;
            }
            $op = isset($ops[$key]) && !empty($ops[$key]) ? $ops[$key] : '%*%';
            if ($this->relationSearch && count(explode('.', $key)) == 1) {
                $key = "{$tableName}.{$key}";
            }
            switch (strtolower($op)) {
                case '=':
                    $where[] = [$key, '=', $val];
                    break;
                case '%*%':
                    $where[] = [$key, 'LIKE', "%{$val}%"];
                    break;
                case '*%':
                    $where[] = [$key, 'LIKE', "{$val}%"];
                    break;
                case '%*':
                    $where[] = [$key, 'LIKE', "%{$val}"];
                    break;
                case 'range':
                    [$beginTime, $endTime] = explode(' - ', $val);
                    $where[] = [$key, '>=', strtotime($beginTime)];
                    $where[] = [$key, '<=', strtotime($endTime)];
                    break;
                default:
                    $where[] = [$key, $op, "%{$val}"];
            }
        }
        return [$page, $limit, $where, $excludes];
    }

    /**
     * 下拉选择列表
     * @return \think\response\Json
     */
    public function selectList()
    {
        $fields = input('selectFields');
        $data = $this->model
            ->where($this->selectWhere)
            ->field($fields)
            ->select();
        $this->success(null, $data);
    }

    /**
     * 小按钮首页
     */
    public function min_menu_index($class, $field, $with){
        $id = $this->request->param('id/d',0);
        empty($id) && $this->error('提交参数出错');

        if (input('selectFields')) {
            return $this->selectList();
        }
        list($page, $limit, $where) = $this->buildTableParames();

        // 关联字段
        $map[] = [$field, '=', $id];

        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            $count = $class::with($with)
                    ->where($where)
                    ->where($map)
                    ->count();
            $list = $class::with($with)
                    ->where($where)
                    ->where($map)
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('source_id', $id);
        return $this->fetch();
    }

    /**
     * 小按钮新增
     */
    public function min_menu_add($class, $field, $rule = [])
    {
        $source_id = $this->request->param('source_id/d');
        empty($source_id) && $this->error('提交参数出错');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->validate($post, $rule);

            // 关联字段
            $post[$field] = $source_id;

            try {
                $save = (new $class)->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('source_id', $source_id);
        return $this->fetch();
    }

    /**
     * 小按钮编辑
     */
    public function min_menu_edit($class, $rule = [])
    {
        $row = $class::find($this->request->param('id/d'));
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 小按钮删除
     */
    public function min_menu_delete($class)
    {
        $row = $class::whereIn('id', $this->request->param('id'))->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @notes 体温记录公共方法
     * @Author: lxq
     * @param string $with
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @date 2021/10/19 10:53
     */
    public function temperature_index_common(string $with)
    {
        $id = $this->request->param('id/d',0);
        empty($id) && $this->error('提交参数出错');

        $id_card = $this->model->where('id', $id)->value('id_card');

        if (input('selectFields')) {
            return $this->selectList();
        }
        list($page, $limit, $where) = $this->buildTableParames();

        // 关联字段
        $map[] = ['id_card', '=', $id_card];

        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            $count = Form7::with([$with])
                ->where($where)
                ->where($map)
                ->count();
            $list = Form7::with([$with])
                ->where($where)
                ->where($map)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('source_id', $id);
        return $this->fetch();
    }

    /**
     * @notes 体温填报公共方法
     * @Author: lxq
     * @return mixed
     * @date 2021/10/19 10:53
     */
    public function temperature_add_common()
    {
        $id = $this->request->param('id/d',0);
        empty($id) && $this->error('提交参数出错');

        $res = $this->model->where('id', $id)->find();
        empty($res) && $this->error('体温对象不存在');

        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'temperature|体温' =>  'require|float|between:30,45',
            ];
            $this->validate($post, $rule);
            try {
                $data = [
                    'name'          =>  $res->name,
                    'id_card'       =>  $res->id_card,
                    'mobile'        =>  $res->mobile,
                    'temperature'   =>  $post['temperature'],
                ];
                if (Form7::whereDay('create_time')->where('id_card', $data['id_card'])->count() >= 2 ){
                    throw new Exception('每天最多只能提交两次体温');
                }
                $time1 = date('Y-m-d 00:00:00', time());
                $time2 = date('Y-m-d 14:00:00', time());
                $time3 = date('Y-m-d 23:59:59', time());
                //查询上午体温是否填报
                $morning = Form7::where('id_card', $data['id_card'])->whereBetweenTime('create_time', $time1, $time2)->count();
                //查询下午体温是否填报
                $afternoon = Form7::where('id_card', $data['id_card'])->whereBetweenTime('create_time', $time2, $time3)->count();
                if ((time() < strtotime($time2)) && $morning > 0) {
                    throw new Exception('今日上午已经填报过体温了');
                }
                if ((time() < strtotime($time3)) && (time() >= strtotime($time2)) && $afternoon > 0) {
                    throw new Exception('今日下午已经填报过体温了');
                }

                //体温报警记录
                if ($post['temperature'] > 37.3) {
                    (new TemperatureAlarm())->save($data);
                }
                Form7::create($data);
            } catch (\Exception $e) {
                $this->error('保存失败：'.$e->getMessage());
            }
            $this->success('保存成功');
        }
        $this->assign('res', $res);
        return $this->fetch();
    }
}
